<template>
  <uni-popup ref="popupRef" :is-mask-click="false">
    <view class="popup">
      <editItem :item="item" @update:item="handleUpdateItem" :showClassid="true"/>
      <view class="operate-btn">
        <button type="primary" size="mini" @click="handleSave">保存</button>
        <button type="warn" size="mini" @click="cancel">取消</button>
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref } from 'vue';
import editItem from './editItem.vue';
import { showToast, uploadFile } from '@/utils/common';
import { cloudToHttp } from '@/utils/tools';
const picCloudObj = uniCloud.importObject('admin-bizhi-picture');
const imageCloudObj = uniCloud.importObject('handle-image');
const props = defineProps({
  item: {
    type: Object,
    default: () => ({}),
  },
});
const emits = defineEmits(['update:item']);
const popupRef = ref(null);
const open = () => {
  popupRef.value.open();
};
const close = () => {
  popupRef.value.close();
};

const handleSave = async () => {
  let picurl = props.item.picurl;
  let file;
  if (props.item.tempurl && props.item.tempurl != props.item.picurl) {
    file = await uploadFile(props.item.tempurl);
    picurl = cloudToHttp(file.fileID);
  }
  const { tempurl, ...params } = props.item;
  const res = await picCloudObj.update({ ...params, picurl });
  if (res.errCode === 0) {
    showToast({
      title: '保存成功',
    });

    if (file) {
      imageCloudObj.remove(props.item.picurl);
    }

    close();
    emits('success');
  } else {
    showToast({
      title: res.errMsg,
    });
  }
};
const cancel = () => {
  popupRef.value.close();
};
const handleUpdateItem = (e) => {
  emits('update:item', e);
};
defineExpose({
  open,
  close,
});
</script>

<style scoped lang="less">
.popup {
  width: 600px;
  min-height: 300px;
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
}
</style>
